package com.ocean.sort;

import java.util.Arrays;

public class MergeSort2 {
    public static void main(String[] args) {
        MergeSort2 mergeSort = new MergeSort2();
        int[] nums = {8, 3, 9, 7, 1, 2, 5};
        mergeSort.mergeSort(nums, nums.length);
        System.out.println(Arrays.toString(nums));
    }

    private void mergeSort(int[] nums, int n) {
        mergeSort(nums, 0, n - 1);
    }

    private void mergeSort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2; // 3 1
        mergeSort(nums, start, mid);
        mergeSort(nums, mid + 1, end);
        merge(nums, start, mid, end);
    }


    private void merge(int[] nums, int start, int mid, int end) {
        int[] temp = new int[(end - start) + 1];
        int left = start;
        int right = mid + 1;
        for (int i = 0; i < temp.length; i++) {
            if (left > mid) {
                temp[i] = nums[right++];
            } else if (right > end) {
                temp[i] = nums[left++];
            } else if (nums[left] < nums[right]) {
                temp[i] = nums[left++];
            } else {
                temp[i] = nums[right++];
            }
        }
        for (int i = 0; i < temp.length; i++) {
            nums[start + i] = temp[i];
        }

    }


}
